import type { SevenCode, SevenCodeItem } from "../entity/type"
import { ref, watch } from "vue"
import { getByTypeApplicabilityApi, getDomainApi } from "../entity"
import { isEmpty } from "lodash"

/**
 * 七码选择器 Composable
 * 优化数据加载和级联关系处理
 */
export function useFetchSevenCode() {
  // 各级选项数据
  const kindOptions = ref<SevenCodeItem[]>([])
  const domainOptions = ref<SevenCodeItem[]>([])
  const countryOptions = ref<SevenCodeItem[]>([])
  const categoryOptions = ref<SevenCodeItem[]>([])
  const subCategoryOptions = ref<SevenCodeItem[]>([])
  const specificOptions = ref<SevenCodeItem[]>([])
  const extraOptions = ref<SevenCodeItem[]>([])

  // 加载状态
  const loading = ref({
    kind: false,
    domain: false,
    country: false,
    category: false,
    subcategory: false,
    specific: false,
    extra: false
  })

  // 七码数据
  const sevencode = ref<SevenCode>({
    kind: -1,
    domain: -1,
    country: -1,
    category: -1,
    subcategory: -1,
    specific: -1,
    extra: -1
  })

  // 获取种类选项
  const getKindOptions = async () => {
    if (loading.value.kind) return
    loading.value.kind = true

    try {
      const { data } = await getByTypeApplicabilityApi({ type: "kind" })
      kindOptions.value = data || []
    } catch (error) {
      kindOptions.value = []
    } finally {
      loading.value.kind = false
    }
  }

  // 获取领域选项
  const getDomainOptions = async () => {
    if (sevencode.value.kind == undefined || sevencode.value.kind == -1) {
      domainOptions.value = []
      return
    }
    if (sevencode.value.kind === -1 || loading.value.domain) return
    loading.value.domain = true


    try {
      const { data } = await getDomainApi(sevencode.value.kind)
      domainOptions.value = data || []
    } catch (error) {
      domainOptions.value = []
    } finally {
      loading.value.domain = false
    }
  }

  // 获取国家选项
  const getCountryOptions = async () => {
    if (loading.value.country) return
    loading.value.country = true
    try {
      const { data } = await getByTypeApplicabilityApi({ type: "country" })
      countryOptions.value = data || []
    } catch (error) {
      countryOptions.value = []
    } finally {
      loading.value.country = false
    }
  }

  // 获取类别选项
  const getCategoryOptions = async () => {
    if (sevencode.value.country == undefined || sevencode.value.country == -1) {
      categoryOptions.value = []
      return
    }
    if (sevencode.value.country === -1 || loading.value.category) return
    loading.value.category = true

    try {
      const { data } = await getByTypeApplicabilityApi({
        type: "category",
        applicability: `${sevencode.value.kind},${sevencode.value.domain},${sevencode.value.country}`
      })
      categoryOptions.value = data || []
    } catch (error) {
      categoryOptions.value = []
    } finally {
      loading.value.category = false
    }
  }

  // 获取子类选项
  const getSubCategoryOptions = async () => {
    if (sevencode.value.kind == undefined || sevencode.value.category == -1) {
      subCategoryOptions.value = []
      return
    }
    if (sevencode.value.category === -1 || loading.value.subcategory) return
    loading.value.subcategory = true

    try {
      const { data } = await getByTypeApplicabilityApi({
        type: "subCategory",
        applicability: `${sevencode.value.kind},${sevencode.value.domain},${sevencode.value.country},${sevencode.value.category}`
      })
      subCategoryOptions.value = data || []
    } catch (error) {
      subCategoryOptions.value = []
    } finally {
      loading.value.subcategory = false
    }
  }

  // 获取具体型号选项
  const getSpecificOptions = async () => {
    if (sevencode.value.kind == undefined || sevencode.value.subcategory == -1) {
      specificOptions.value = []
      return
    }
    if (sevencode.value.subcategory === -1 || loading.value.specific) return
    loading.value.specific = true

    try {
      const { data } = await getByTypeApplicabilityApi({
        type: "specific",
        applicability: `${sevencode.value.kind},${sevencode.value.domain},${sevencode.value.country},${sevencode.value.category},${sevencode.value.subcategory}`
      })
      specificOptions.value = data || []
    } catch (error) {
      specificOptions.value = []
    } finally {
      loading.value.specific = false
    }
  }

  // 获取拓展型号选项
  const getExtraOptions = async () => {
    if (sevencode.value.kind == undefined || sevencode.value.specific == -1) {
      extraOptions.value = []
      return
    }
    if (sevencode.value.specific === -1 || loading.value.extra) return
    loading.value.extra = true

    try {
      const { data } = await getByTypeApplicabilityApi({
        type: "extra",
        applicability: `${sevencode.value.kind},${sevencode.value.domain},${sevencode.value.country},${sevencode.value.category},${sevencode.value.subcategory},${sevencode.value.specific}`
      })
      extraOptions.value = data || []
    } catch (error) {
      extraOptions.value = []
    } finally {
      loading.value.extra = false
    }
  }

  // 重置后续级联数据
  const resetCascadeData = (level: "kind" | "domain" | "country" | "category" | "subcategory" | "specific") => {
    switch (level) {
      case "kind":
        sevencode.value.domain = -1
        domainOptions.value = []
        // 继续向下级联
      case "domain":
        sevencode.value.category = -1
        categoryOptions.value = []
        // 继续向下级联
      case "country":
      case "category":
        sevencode.value.subcategory = -1
        subCategoryOptions.value = []
        // 继续向下级联
      case "subcategory":
        sevencode.value.specific = -1
        specificOptions.value = []
        // 继续向下级联
      case "specific":
        sevencode.value.extra = -1
        extraOptions.value = []
        break
    }
  }

  // 种类变更处理
  const kindChange = (value: number) => {
    sevencode.value.kind = value
    resetCascadeData("kind")
    getDomainOptions()
  }

  // 领域变更处理
  const domainChange = (value: number) => {
    sevencode.value.domain = value
    resetCascadeData("domain")
    getCategoryOptions()
  }

  // 国家变更处理
  const countryChange = (value: number) => {
    sevencode.value.country = value
    resetCascadeData("country")
    getCategoryOptions()
  }

  // 类别变更处理
  const categoryChange = (value: number) => {
    sevencode.value.category = value
    resetCascadeData("category")
    getSubCategoryOptions()
  }

  // 子类变更处理
  const subcategoryChange = (value: number) => {
    sevencode.value.subcategory = value
    resetCascadeData("subcategory")
    getSpecificOptions()
  }

  // 具体型号变更处理
  const specificChange = (value: number) => {
    sevencode.value.specific = value
    resetCascadeData("specific")
    getExtraOptions()
  }

  // 拓展型号变更处理
  const extraChange = (value: number) => {
    sevencode.value.extra = value
  }

  // 初始化和监听变化
  watch(
    () => sevencode.value,
    (newVal, oldVal) => {
      // 只在初始化或特定值变化时加载数据，避免不必要的请求
      if (!oldVal || oldVal.kind !== newVal.kind) {
        getDomainOptions()
      }

      if (!oldVal || oldVal.country !== newVal.country || oldVal.domain !== newVal.domain || oldVal.kind !== newVal.kind) {
        getCategoryOptions()
      }

      if (!oldVal || oldVal.category !== newVal.category) {
        getSubCategoryOptions()
      }

      if (!oldVal || oldVal.subcategory !== newVal.subcategory) {
        getSpecificOptions()
      }

      if (!oldVal || oldVal.specific !== newVal.specific) {
        getExtraOptions()
      }
    },
    { immediate: true, deep: true }
  )

  // 初始加载基础数据
  getKindOptions()
  getCountryOptions()

  return {
    kindOptions,
    domainOptions,
    countryOptions,
    categoryOptions,
    subCategoryOptions,
    specificOptions,
    extraOptions,
    sevencode,
    loading,
    kindChange,
    domainChange,
    countryChange,
    categoryChange,
    subcategoryChange,
    specificChange,
    extraChange
  }
}
